// pages/food2/food2.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isHiddMask: true,
    totalMoney: 0,
    totalNum: 0,
    cartList: [], //购物车数据
    currentIndex: 0,
    foodType: '早点',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getTabs()
  },
  // 获取分类
  getTabs() {
    const $ = db.command.aggregate
    db.collection('dishes').aggregate()
      .group({
        _id: '$Category',
      })
      .end()
      .then(res => {
        console.log('菜品分类', res)
        this.setData({
          tabs: res.list,
        })
        this.getList()
      })
  },
  // 点击分类列表
  selectTab(e) {
    this.setData({
      currentIndex: e.currentTarget.dataset.index
    })
    this.getList()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabs()
  },

  //获取菜品数据
  getList() {
    let cartList = wx.getStorageSync('cart') || []
    console.log('本地缓存的购物车数据', this.data.tabs[this.data.currentIndex]._id)
    this.setData({
      cartList: cartList,
      foodType: this.data.tabs[this.data.currentIndex]._id,
    })
    db.collection('dishes')
      .where({
        Category: this.data.tabs[this.data.currentIndex]._id,
      })
      .get()
      .then(res => {
        console.log('获取到的菜品数据', res)
        let list = res.data
        if (list && list.length > 0) {
          list.forEach(item => {
            if (cartList && cartList.length > 0) {
              //查询购物车数组里是否存在当前点击的菜品
              var result = cartList.find(cart => {
                return cart._id == item._id
              })
              console.log('是否存在于购物车里', result)
              if (result) {
                item.num = result.num
              } else {
                item.num = 0
              }
            } else {
              item.num = 0
            }
          })
          this.setData({
            foodList: list,
          })
          this.getTotal()
        }
      })
      .catch(res => {
        console.log('搜索失败', res)
      })
  },
  //点击增加
  add(e) {
    //console.log('点击了加号',e.currentTarget.dataset.id)
    let id = e.currentTarget.dataset.id
    let list = this.data.foodList
    console.log('当前菜品', list)
    let cartList = this.data.cartList
    // let totalMoney = this.data.totalMoney
    // let totalNum = this.data.totalNum
    list.forEach(item => {
      if (item._id == id) {
        item.num += 1;
        // totalMoney += item.price
        // totalNum += 1;
        if (cartList && cartList.length > 0) {
          //查询购物车数组里是否存在当前点击的菜品
          var result = cartList.find(cart => {
            return cart._id == id
          })
          console.log("当前点击的菜品是否存在于购物车里", result)
          if (!result) { //如果点击的菜品不在购物车里
            cartList.push(item)
          } else {
            result.num = item.num
          }
        } else {
          cartList.push(item)
        }

        // this.setData({
        //   totalMoney: this.data.totalMoney += item.price,
        //   totalNum: this.data.totalNum += 1,
        //   cartList:this.data.cartList.push(item)
        // })
      }
    })
    console.log('遍历购物车列表', this.data.cartList)
    this.setData({
      foodList: list,
      //totalMoney, //totalMoney:totalMoney
      //totalNum,
      cartList,
    })
    this.getTotal()
    wx.setStorageSync('cart', cartList)
  },
  //点击减少
  sub(e) {
    console.log('点击了减号', e.currentTarget.dataset.id)
    let id = e.currentTarget.dataset.id
    let list = this.data.foodList
    console.log('当前菜品', list)
    let cartList = this.data.cartList
    list.forEach(item => {
      if (item._id == id) {
        if (item.num > 0) {
          item.num -= 1;
          //查询购物车数组里是否存在当前点击的菜品
          var index = cartList.findIndex(cart => {
            return cart._id == id
          })
          if (index > -1) {
            cartList[index].num = item.num
          }
          //console.log("当前点击的菜品是否存在于购物车里",result)
          if (item.num == 0) { //如果点击的菜品数量为0，则移除购物车
            cartList.splice(index, 1) //删除下标为index的元素
          }
        } else {
          wx.showToast({
            title: '数量为0',
            icon: 'none'
          })
        }
      }

    })
    console.log('遍历后的菜品', list)
    this.setData({
      foodList: list,
      //totalMoney, //totalMoney:totalMoney
      //totalNum,
      cartList,
    })
    this.getTotal()
    wx.setStorageSync('cart', cartList)
  },

  //计算总价格和总数量
  getTotal() {
    let cartList = this.data.cartList
    let totalMoney = 0
    let totalNum = 0

    cartList.forEach(item => {
      totalMoney += item.num * item.price
      totalNum += item.num
    })
    this.setData({
      totalNum,
      totalMoney,
    })
  },

  //关闭购物车
  closeMask() {
    this.setData({
      isHiddMask: true
    })
  },

  //打开购物车
  openMask() {
    this.setData({
      isHiddMask: false
    })
  },

  //清空购物车
  clear_cart() {
    let foodList = this.data.foodList
    foodList.forEach(item => {
      item.num = 0;
    })
    this.setData({
      foodList,
      cartList: [],
      totalMoney: 0,
      totalNum: 0,
    })
    wx.setStorageSync('cart', null)
  },

  //删除购物车里的一条数据
  closeCartItem(e) {
    console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index
    let cartList = this.data.cartList
    let cart = cartList[index]
    //遍历菜品列表把要删除的菜品的数量置为0
    let foodList = this.data.foodList
    foodList.forEach(item => {
      if (cart._id == item._id) {
        item.num = 0;
      }
    })
    //从购物车数组删除当前菜品
    cartList.splice(index, 1)
    this.setData({
      cartList,
      foodList,
    })
    //重新计算总价格，总数量
    this.getTotal()
    //把更新后的数据重新缓存
    wx.setStorageSync('cart', cartList)
  },
  goOrder() {
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})